<template>
  <div>
    <div>
      <input
        ref="addFileInput"
        type="file"
        accept="image/jpeg, image/bmp, image/png, image/webp"
        style="display: none"
        @change="onAddFileChange()"
      >
      <!-- 功能区域开始  -->
      <div class="workbench">
        <div class="remove-header">
          <div class="controls__center">
            <span
              class="undo"
              :class="{ disabled: !undoOperate }"
              @click="undo"
            >上一步</span>
            <span
              class="redo"
              :class="{ disabled: !redoOperate }"
              @click="redo"
            >下一步</span>
          </div>
        </div>
        <div class="tool-bar">
          <div
            class="brush"
            :class="{ active: currentTool === 'brush' }"
            @click="chooseTool('brush')"
          >
            笔刷
            <div
              v-if="isShowBrushSize && currentTool === 'brush'"
              class="brush-size"
              style="min-width: 300px"
            >
              <div>
                <span>笔刷大小</span>
                <span>{{ brushSize }}px</span>
              </div>
              <el-slider
                v-model="brushSize"
                :min="1"
                :max="500"
                @input="changeSize"
                @change="changeSizeOver"
              />
            </div>
          </div>
          <div
            class="rectangle"
            :class="{ active: currentTool === 'addRectangle' }"
            @click="chooseTool('addRectangle')"
          >
            框选
          </div>
          <div
            class="noose"
            :class="{ active: currentTool === 'noose' }"
            @click="chooseTool('noose')"
          >
            套索
          </div>
          <div
            class="eraser"
            :class="{ active: currentTool === 'eraser' }"
            @click="chooseTool('eraser')"
          >
            橡皮擦
            <div
              v-if="isShowBrushSize && currentTool === 'eraser'"
              class="brush-size"
            >
              <div>
                <span>笔刷大小</span>
                <span>{{ brushSize }}px</span>
              </div>
              <el-slider
                v-model="brushSize"
                :min="1"
                :max="500"
                @input="changeSize"
                @change="changeSizeOver"
              />
            </div>
          </div>
          <div class="line6" />
          <div class="workbtn begin" @click="onConfirm()">完成</div>
        </div>
        <div
          v-show="!mobileImgDownload"
          class="middle"
          :class="{ mobile: isMobile }"
        >
          <div
            ref="preview-wrapper"
            class="preview-wrapper"
            :class="{ 'brush-change': brushChange }"
          >
            <div
              v-if="
                appStatus === 'uploading' ||
                  appStatus === 'processing' ||
                  appStatus === 'finished' ||
                  appStatus === 'finished-success' ||
                  appStatus === 'finished-error'
              "
              class="process-info"
            >
              <div v-if="appStatus === 'uploading'" class="processing">
                <p class="p1">
                  <span class="circle" />
                </p>
                <p class="p2">正在处理中...</p>
              </div>
              <div v-if="appStatus === 'processing'" class="processing">
                <p v-if="currentDisplayProcessFile" class="p1">
                  <span class="circle" />
                </p>
                <p v-if="currentDisplayProcessFile" class="p2">正在处理中...</p>
              </div>
              <div
                v-if="
                  appStatus === 'finished' ||
                    appStatus === 'finished-success' ||
                    appStatus === 'finished-error'
                "
                class="finished"
                :class="{
                  success: appStatus === 'finished-success',
                  error: appStatus === 'finished-error',
                }"
              >
                <p class="close" @click="appStatus = 'editing'" />
                <p class="p22">失败, 请稍后重试！</p>
              </div>
            </div>
            <div
              id="preview-container"
              class="preview-container"
              @mouseup="wrapUp($event)"
              @mousedown="wrapDown($event)"
              @mousemove="wrapMove($event)"
              @mouseleave="wrapLeave($event)"
              @mousewheel="wrapWheel($event)"
            >
              <canvas
                id="canvas"
                ref="canvas"
                @mouseup="onMouseUp($event)"
                @mousedown="onMouseDown($event)"
                @mousemove="onMouseMove($event)"
                @mouseleave="onMouseLeave($event)"
                @touchend="onMouseUp($event)"
                @touchstart="onMouseDown($event)"
                @touchmove="onMouseMove($event)"
              />
              <canvas
                id="upper-canvas"
                ref="upper-canvas"
                :class="{
                  cursorstyle:
                    currentTool === 'brush' || currentTool === 'eraser',
                  'cursor-rect': currentTool === 'addRectangle',
                  'cursor-tl': cursorRect === 'tl' && operation != 'creating',
                  'cursor-bl': cursorRect === 'bl',
                  'cursor-tr': cursorRect === 'tr',
                  'cursor-br': cursorRect === 'br' && operation != 'creating',
                  'cursor-move': cursorRect === 'moving',
                  'cursor-noose': currentTool === 'noose',
                }"
                @mouseup="onMouseUp($event)"
                @mousedown="onMouseDown($event)"
                @mousemove="onMouseMove($event)"
                @mouseleave="onMouseLeave($event)"
                @touchend="onMouseUp($event)"
                @touchstart="onMouseDown($event)"
                @touchmove="onMouseMove($event)"
              />
              <div ref="item" class="item-container">
                <img
                  v-if="selectedFile"
                  style="width: 100%; height: 100%"
                  draggable="false"
                  :src="
                    selectedFile.processed_url != null
                      ? selectedFile.processed_url
                      : selectedFile.url
                  "
                >
              </div>
            </div>
            <div class="scale-center">
              <span
                class="pan"
                :class="{ active: currentTool === 'move' }"
                @click="chooseTool('move')"
              />
              <span class="zoom-out" @click="zoomOut" />
              <span
                class="zoom-size"
              >{{ Number(zoomLevel * 100).toFixed(0) }}%</span>
              <span class="zoom-in" @click="zoomIn" />
            </div>
          </div>
          <div class="operations-mobile">
            <div class="tool-list">
              <el-slider
                v-if="isMobile"
                v-model="brushSize"
                :min="1"
                :max="30"
              />
              <span
                class="workbtn begin"
                @click="submit(false)"
              >开始去除水印</span>
              <div class="step">
                <span
                  class="undo"
                  :class="{ disabled: !undoOperate }"
                  @click="undo"
                />
                <span
                  class="redo"
                  :class="{ disabled: !redoOperate }"
                  @click="redo"
                />
              </div>
            </div>
            <div class="btns">
              <div
                class="add-btn workbtn"
                :class="{
                  active:
                    appStatus !== 'uploading' && appStatus !== 'processing',
                }"
                @click="addFile('image', 'reAddFile')"
              >
                添加图片
              </div>
              <div
                class="workbtn download"
                :class="{ disabled: downloadNum === 0 }"
                @click="downloadFinished()"
              >
                下载图片
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Storage from './storage'
// import "@/styles/framework.css";
import '@/styles/removeUnwantedObject.css'
import { isMobile, isMac } from './is'
import closeIconImageUrl from '@/assets/img/close.png'
import top_leftUrl from '@/assets/img/top-left.png'
import top_rightUrl from '@/assets/img/top-right.png'
import bottom_leftUrl from '@/assets/img/bottom-left.png'
import bottom_rightUrl from '@/assets/img/bottom-right.png'

function getDistance(p1, p2) {
  const x = p2.pageX - p1.pageX
  const y = p2.pageY - p1.pageY
  return Math.sqrt(x * x + y * y)
}
function getBase64Image(img) {
  var canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  var ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, img.width, img.height)
  var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
  var dataURL = canvas.toDataURL('image/' + ext)

  return dataURL
}
function btof(data, fileName) {
  const dataArr = data.split(',')
  const byteString = atob(dataArr[1])

  const options = {
    type: 'image/jpeg',
    endings: 'native'
  }
  const u8Arr = new Uint8Array(byteString.length)
  for (let i = 0; i < byteString.length; i++) {
    u8Arr[i] = byteString.charCodeAt(i)
  }
  return new File([u8Arr], fileName + '.jpg', options)
}

var mousePressed = false
var selectFilePressed = false // eslint-disable-line no-unused-vars
var lastX, lastY // eslint-disable-line no-unused-vars
var movePointId
var closePath = false // eslint-disable-line no-unused-vars
var closeIconImage = new Image()
var startX, startY
var transX = 0
var transY = 0
var tempath = []
var MessageBox = {}
var startTouch = [] // 移动端双指缩放
var istouch = false
closeIconImage.setAttribute('crossOrigin', 'anonymous')
closeIconImage.src = closeIconImageUrl

// var arrowA = new Image();
// arrowA.setAttribute("crossOrigin", "anonymous");
// arrowA.src = arrowAUrl;

// var arrowB = new Image();
// arrowB.setAttribute("crossOrigin", "anonymous");
// arrowB.src = arrowBUrl;

var top_left = new Image()
top_left.setAttribute('crossOrigin', 'anonymous')
top_left.src = top_leftUrl

var top_right = new Image()
top_right.setAttribute('crossOrigin', 'anonymous')
top_right.src = top_rightUrl

var bottom_left = new Image()
bottom_left.setAttribute('crossOrigin', 'anonymous')
bottom_left.src = bottom_leftUrl

var bottom_right = new Image()
bottom_right.setAttribute('crossOrigin', 'anonymous')
bottom_right.src = bottom_rightUrl

// var moveIcon = new Image();
// moveIcon.setAttribute("crossOrigin", "anonymous");
// moveIcon.src = moveIconUrl;

// var appliedIcon = new Image();
// appliedIcon.setAttribute("crossOrigin", "anonymous");
// appliedIcon.src = appliedIconUrl;

// var toApplyIcon = new Image();
// toApplyIcon.setAttribute("crossOrigin", "anonymous");
// toApplyIcon.src = toApplyIconUrl;

var bartimer90

export default {
  // extends: partners,
  data() {
    return {
      isShow: false,
      isMobile: isMobile,
      showRight: !isMobile,
      zoomLevel: 1,
      currentTool: 'brush', // rectangle、noose
      brushSize: isMobile ? 10 : 48,
      isShowBrushSize: true,
      undoOperate: false,
      redoOperate: false,
      downloadNum: 0,

      initialized: false,
      client: null,

      selectedFile: null,
      currentRouter: 'uploader',

      uploaded: 0,
      uploadQueue: [],
      currentUploadQueue: [],
      fileList: [],

      pictureFileExtensions: ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff'],

      processedNumber: 0,
      processedSuccessNumber: 0,
      processedFailNumber: 0,

      currentDisplayProcessFile: null,

      appStatus: '', // app 状态, 'uploading', 'uploaded', 'editing', 'processing', 'finished'

      showConfirm: false,

      resourceType: null, // 'image', 'video'

      padding: 10, // 水印框点击padding

      previousEvent: null,

      movingRectangleId: null,
      resizingRectangleId: null,
      // applyingToOthersRectangleId: null,
      resizeTarget: null,
      operation: null, // 'moving', 'creating'， 'deleting', 'resizing', 'applyingToOthers'
      cursorRect: null, // 鼠标状态
      canvasInterval: null,

      somethingOk: '好的',
      somethingError: false,
      modalMsg: '',
      errortip: '失败，请稍后重试！',
      lang: document.documentElement.lang || '',
      modalAppStatus: 'upload', // app引导弹窗
      processNum: 1,
      showModalApp: false,
      preBrushSize: 48,
      brushChange: false, // 滑动的问题
      mobileImgDownload: false // 移动端长按下载
    }
  },
  computed: {},
  async mounted() {
    this.dragControllerDiv()
    this.bodyAddDragenter()
  },
  destroyed() {
    clearInterval(this.canvasInterval)
  },
  created: async function() {
    console.log('remove created()')
    // test
    // let file = Storage.get("imgInfo");
    // let file = {
    //   name: "index_wyc.png",
    //   resource_id: "efac851f-4cd6-46d5-8a16-e585caa25191",
    //   resource_id2: "efac851f-4cd6-46d5-8a16-e585caa25191",
    //   task_id: null,
    //   upload_progress: 1,
    //   process_progress: 0,
    //   query_interval: null,
    //   processed_url: null,
    //   processed_url2:
    //     "https://picwishsz.oss-cn-shenzhen.aliyuncs.com/tasks/input/watermark/9e25d507-f6bb-4c0c-a5b4-106a703d942a.png?Expires=1655425080&OSSAccessKeyId=LTAI5tGjJnh66c1txANiRBQN&Signature=6WByPdaJnFF7U5zzn3HemThVB0M%3D",
    //   key: "tasks/input/watermark/9e25d507-f6bb-4c0c-a5b4-106a703d942a.png",
    //   status: "uploaded",
    //   url: "https://picwishsz.oss-cn-shenzhen.aliyuncs.com/tasks/input/watermark/9e25d507-f6bb-4c0c-a5b4-106a703d942a.png?Expires=1655425080&OSSAccessKeyId=LTAI5tGjJnh66c1txANiRBQN&Signature=6WByPdaJnFF7U5zzn3HemThVB0M%3D",
    //   type: null,
    //   width: 750,
    //   height: 234,
    //   afterWidth: null,
    //   afterHeight: null,
    //   historyArray: [],
    //   hStep: -1,
    //   brushPath: [],
    //   points: [],
    //   eraserPath: [],
    //   rectangles: [],
    //   touched: true,
    //   image_thumb_url: null,
    // };
    // if (file) {
    //   this.selectFile(file);
    // }
  },
  methods: {
    backhome() {
      if (this.mobileImgDownload) {
        this.mobileImgDownload = false
        return
      }
      document.getElementById('ap-header').style.display = 'block'
      document.getElementsByTagName('footer')[0].style.display = 'block'
      if (document.getElementsByClassName('talkie-container').length > 0) {
        document.getElementsByClassName('talkie-container')[0].style.display =
          'block'
      }
      if (document.getElementById('chat-widget-container')) {
        document.getElementById('chat-widget-container').style.display =
          'block'
      }
      if (document.getElementsByClassName('wechatbox').length > 0) {
        document.getElementsByClassName('wechatbox')[0].style.display = 'block'
      }

      this.currentRouter = 'uploader'
      this.uploadQueue = []
      this.selectedFile = null
      this.downloadNum = 0
      this.currentTool = 'brush'
      this.isShowBrushSize = true
      this.brushSize = 48
      this.preBrushSize = 48
    },

    setTransform(zoomLevel, moveX, moveY, zoom) {
      if (zoom) {
        let translateX = 0
        let translateY = 0
        const str = this.$refs['item'].style.transform
        if (str.indexOf('translate3d') > -1) {
          translateX = parseFloat(
            str.substring(str.indexOf('translate3d(') + 12, str.indexOf('px'))
          )
          translateY = parseFloat(
            str.substring(str.indexOf('px,') + 4, str.lastIndexOf('px,'))
          )
        }
        moveX = moveX + translateX
        moveY = moveY + translateY
      }

      this.$refs[
        'item'
      ].style.transform = `scale(${this.zoomLevel},${this.zoomLevel}) translate3d(${moveX}px,${moveY}px,0px)`

      const canvas = this.$refs['canvas']
      canvas.style.transform = `scale(${this.zoomLevel},${this.zoomLevel}) translate3d(${moveX}px,${moveY}px,0px)`

      const upperCanvas = this.$refs['upper-canvas']
      upperCanvas.style.transform = `scale(${this.zoomLevel},${this.zoomLevel}) translate3d(${moveX}px,${moveY}px,0px)`
    },
    zoomOut() {
      if (this.zoomLevel > 0.1) {
        this.zoomLevel = (this.zoomLevel - 0.1).toFixed(1)
        this.setTransform(this.zoomLevel, 0, 0, true)
      }
    },
    zoomIn() {
      if (this.zoomLevel < 4) {
        this.zoomLevel = (parseFloat(this.zoomLevel) + 0.1).toFixed(1)
        this.setTransform(this.zoomLevel, 0, 0, true)
      }
    },
    selectFile: function(file) {
      if (
        this.selectedFile &&
        this.selectedFile.resource_id === file.resource_id
      ) {
        return
      }
      if (file.status === 'uploading') {
        return false
      }
      this.selectedFile = null
      this.appStatus = 'editing'
      file.touched = true
      this.$nextTick(
        function() {
          this.selectedFile = file
          this.refreshCanvas()
        }.bind(this)
      )
    },
    refreshCanvas: function() {
      // 计算canvas的宽高和位置
      const canvas = this.$refs['canvas']
      var container = this.$refs['preview-wrapper']

      var elementWidth = this.selectedFile.width
      var elementHeight = this.selectedFile.height

      var containerWidth = container.clientWidth
      var containerHeight = container.clientHeight

      var calWidth, calHeight

      if (
        this.selectedFile.width < containerWidth &&
        this.selectedFile.height < containerHeight
      ) {
        calWidth = this.selectedFile.width
        calHeight = this.selectedFile.height
      } else {
        if (containerWidth / containerHeight >= elementWidth / elementHeight) {
          var width = (containerHeight / elementHeight) * elementWidth
          calWidth = width
          calHeight = containerHeight
        } else {
          var height = (containerWidth / elementWidth) * elementHeight
          calWidth = containerWidth
          calHeight = height
        }
      }
      canvas.setAttribute('width', calWidth)
      canvas.setAttribute('height', calHeight)

      this.$refs['item'].style.width = calWidth + 'px'
      this.$refs['item'].style.height = calHeight + 'px'

      this.selectedFile.afterWidth = calWidth
      this.selectedFile.afterHeight = calHeight

      const upperCanvas = this.$refs['upper-canvas']
      upperCanvas.setAttribute('width', calWidth)
      upperCanvas.setAttribute('height', calHeight)

      selectFilePressed = true
      this.zoomLevel = 1
      this.setTransform(1, 0, 0, false)

      if (this.selectedFile.hStep > 0) {
        this.undoOperate = true
      } else {
        this.undoOperate = false
      }
      if (this.selectedFile.hStep < this.selectedFile.historyArray.length - 1) {
        this.redoOperate = true
      } else {
        this.redoOperate = false
      }
      this.canvasInterval = setInterval(
        function() {
          this.reDraw()
        }.bind(this),
        10
      )
    },

    chooseTool(type) {
      this.currentTool = type
      if (type === 'brush' || type === 'eraser') {
        this.isShowBrushSize = true
      } else {
        this.isShowBrushSize = false
        const canvas = document.getElementById('upper-canvas')
        const context = canvas.getContext('2d')
        const width = canvas.getAttribute('width')
        const height = canvas.getAttribute('height')
        context.clearRect(0, 0, width, height)
      }
    },
    onMouseDown: function(event) {
      // console.log("down="+ event.touches[0].clientX)
      mousePressed = true
      selectFilePressed = false
      if (this.currentTool === 'brush') {
        this.isShowBrushSize = false

        var brushPath = this.selectedFile.brushPath

        let mobilex
        let mobiley // 移动端的坐标
        if (this.isMobile && !!event.touches) {
          event.preventDefault()
          if (event.touches.length >= 2) {
            // 判断是否有两个点在屏幕上
            istouch = true
            startTouch = event.touches // 得到第一组两个点
            return
          } else {
            const vertex = document
              .getElementById('canvas')
              .getBoundingClientRect()
            mobilex =
              (event.touches[0].clientX - vertex.left) / Number(this.zoomLevel)
            mobiley =
              (event.touches[0].clientY - vertex.top) / Number(this.zoomLevel)
          }
        }
        brushPath.push([
          {
            x: this.isMobile ? mobilex : event.offsetX,
            y: this.isMobile ? mobiley : event.offsetY,
            size: this.brushSize
          }
        ])
      } else if (this.currentTool === 'eraser') {
        this.isShowBrushSize = false
        var eraserPath = this.selectedFile.eraserPath

        let mobilex
        let mobiley // 移动端的坐标
        if (this.isMobile && !!event.touches) {
          event.preventDefault()
          if (event.touches.length >= 2) {
            // 判断是否有两个点在屏幕上
            istouch = true
            startTouch = event.touches // 得到第一组两个点
            return
          } else {
            const vertex = document
              .getElementById('canvas')
              .getBoundingClientRect()
            mobilex =
              (event.touches[0].clientX - vertex.left) / Number(this.zoomLevel)
            mobiley =
              (event.touches[0].clientY - vertex.top) / Number(this.zoomLevel)
          }
        }
        eraserPath.push([
          {
            x: this.isMobile ? mobilex : event.offsetX,
            y: this.isMobile ? mobiley : event.offsetY,
            size: this.brushSize
          }
        ])
      } else if (this.currentTool === 'addRectangle') {
        // 判断当前点击元素
        var isInsideSomeRectangle = false
        var isResizingRectangle = false
        var rectangles = this.selectedFile.rectangles
        for (var i = 0; i < rectangles.length; i++) {
          if (
            (this.resizeTarget = this.checkClickIsResizeRectangle(
              rectangles[i],
              {
                x: event.offsetX,
                y: event.offsetY
              }
            ))
          ) {
            this.resizingRectangleId = rectangles[i].id
            isResizingRectangle = true
            break
          } else if (
            this.checkClickInsideRectangle(rectangles[i], {
              x: event.offsetX,
              y: event.offsetY
            })
          ) {
            this.movingRectangleId = rectangles[i].id
            isInsideSomeRectangle = true
            break
          }
        }
        if (isInsideSomeRectangle) {
          this.operation = 'moving'
        } else if (isResizingRectangle) {
          if (this.resizeTarget === 'tr') {
            this.operation = 'deleting'
          } else {
            this.operation = 'resizing'
          }
        } else {
          this.operation = 'creating'

          const length = this.selectedFile.rectangles.length
          this.selectedFile.rectangles.push({
            id:
              this.selectedFile.rectangles.length > 0
                ? this.selectedFile.rectangles[length - 1].id + 1
                : 0,
            x: event.offsetX,
            y: event.offsetY,
            width: 0,
            height: 0,
            applied: false,
            isHidden: false
          })
        }
      } else if (this.currentTool === 'noose') {
        var points = this.selectedFile.points
        if (points.length < 1) {
          points.push([
            {
              x: event.offsetX,
              y: event.offsetY
            }
          ])
        } else {
          const path = points[points.length - 1]
          if (path[path.length - 1].closePath) {
            for (let i = 0; i < points.length; ++i) {
              if (this.isPointInPath(points[i], event.offsetX, event.offsetY)) {
                this.operation = 'moving'
                startX = event.offsetX
                startY = event.offsetY
                movePointId = i
                tempath = JSON.parse(
                  JSON.stringify(this.selectedFile.points[movePointId])
                )
                return
              }
            }
            if (this.operation !== 'moving') {
              points.push([
                {
                  x: event.offsetX,
                  y: event.offsetY
                }
              ])
            }
          } else {
            path.push({
              x: event.offsetX,
              y: event.offsetY,
              closePath: false
            })
            // 是否闭合路径
            if (path.length > 3) {
              var dx = event.offsetX - path[0].x
              var dy = event.offsetY - path[0].y
              if (dx * dx + dy * dy < 5 * 5) {
                path[path.length - 1].closePath = true
              }
            }
          }
        }
      }
    },

    onMouseMove: function(event) {
      // console.log("move="+ event.touches[0].clientX)

      const canvas = document.getElementById('canvas')
      const canvasHeight = canvas.scrollHeight
      const canvasWidth = canvas.scrollWidth
      if (this.currentTool === 'brush') {
        let mobilex
        let mobiley
        if (this.isMobile && !!event.touches) {
          event.preventDefault()
          if (event.touches.length >= 2 && istouch) {
            const now = event.touches // 得到第二组两个点
            const scale =
              getDistance(now[0], now[1]) /
              getDistance(startTouch[0], startTouch[1]) // 得到缩放比例，getDistance是勾股定理的一个方法
            this.zoomLevel = scale.toFixed(1)
            const moveX =
              (now[0].pageX - startTouch[0].pageX) / Number(this.zoomLevel) +
              transX
            const moveY =
              (now[0].pageY - startTouch[0].pageY) / Number(this.zoomLevel) +
              transY
            this.setTransform(this.zoomLevel, moveX, moveY, false)
            return
          } else {
            const vertex = document
              .getElementById('canvas')
              .getBoundingClientRect()
            mobilex =
              (event.touches[0].clientX - vertex.left) / Number(this.zoomLevel)
            mobiley =
              (event.touches[0].clientY - vertex.top) / Number(this.zoomLevel)
          }
        }
        this.drawCursor(
          this.isMobile ? mobilex : event.offsetX,
          this.isMobile ? mobiley : event.offsetY
        )
        if (mousePressed) {
          var brushPath = this.selectedFile.brushPath
          brushPath[brushPath.length - 1].push({
            x: this.isMobile ? mobilex : event.offsetX,
            y: this.isMobile ? mobiley : event.offsetY
          })
        }
      } else if (this.currentTool === 'eraser') {
        let mobilex
        let mobiley
        if (this.isMobile && !!event.touches) {
          event.preventDefault()
          if (event.touches.length >= 2 && istouch) {
            const now = event.touches // 得到第二组两个点
            const scale =
              getDistance(now[0], now[1]) /
              getDistance(startTouch[0], startTouch[1]) // 得到缩放比例，getDistance是勾股定理的一个方法
            this.zoomLevel = scale.toFixed(1)
            const moveX =
              (now[0].pageX - startTouch[0].pageX) / Number(this.zoomLevel) +
              transX
            const moveY =
              (now[0].pageY - startTouch[0].pageY) / Number(this.zoomLevel) +
              transY
            this.setTransform(this.zoomLevel, moveX, moveY, false)
            return
          } else {
            const vertex = document
              .getElementById('canvas')
              .getBoundingClientRect()
            mobilex =
              (event.touches[0].clientX - vertex.left) / Number(this.zoomLevel)
            mobiley =
              (event.touches[0].clientY - vertex.top) / Number(this.zoomLevel)
          }
        }
        this.drawCursor(
          this.isMobile ? mobilex : event.offsetX,
          this.isMobile ? mobiley : event.offsetY
        )
        if (mousePressed) {
          var eraserPath = this.selectedFile.eraserPath
          eraserPath[eraserPath.length - 1].push({
            x: this.isMobile ? mobilex : event.offsetX,
            y: this.isMobile ? mobiley : event.offsetY
          })
        }
      } else if (this.currentTool === 'addRectangle') {
        // if(mousePressed){
        let movementX, movementY //, calX, calY

        if (event.movementX) {
          movementX = event.movementX / Number(this.zoomLevel)
          movementY = event.movementY / Number(this.zoomLevel)
        } else {
          if (this.previousEvent) {
            movementX =
              (event.screenX - this.previousEvent.screenX) /
              Number(this.zoomLevel)
            movementY =
              (event.screenY - this.previousEvent.screenY) /
              Number(this.zoomLevel)
          }
        }

        if (this.operation === 'moving') {
          const index = this.selectedFile.rectangles.findIndex(
            function(ele) {
              return ele.id === this.movingRectangleId
            }.bind(this)
          )

          if (this.selectedFile.rectangles[index].x + movementX < 0) {
            this.selectedFile.rectangles[index].x = 0
          } else if (
            this.selectedFile.rectangles[index].x +
              movementX +
              this.selectedFile.rectangles[index].width >
            canvasWidth
          ) {
            this.selectedFile.rectangles[index].x =
              canvasWidth - this.selectedFile.rectangles[index].width
          } else {
            this.selectedFile.rectangles[index].x =
              this.selectedFile.rectangles[index].x + movementX
          }

          if (this.selectedFile.rectangles[index].y + movementY < 0) {
            this.selectedFile.rectangles[index].y = 0
          } else if (
            this.selectedFile.rectangles[index].y +
              movementY +
              this.selectedFile.rectangles[index].height >
            canvasHeight
          ) {
            this.selectedFile.rectangles[index].y =
              canvasHeight - this.selectedFile.rectangles[index].height
          } else {
            this.selectedFile.rectangles[index].y =
              this.selectedFile.rectangles[index].y + movementY
          }
        } else if (this.operation === 'creating') {
          var length = this.selectedFile.rectangles.length
          var calWidth =
            this.selectedFile.rectangles[length - 1].width + movementX
          var calHeight =
            this.selectedFile.rectangles[length - 1].height + movementY
          if (calWidth < 0 || calHeight < 0) {
            return false
          }
          this.selectedFile.rectangles[length - 1].width = calWidth
          this.selectedFile.rectangles[length - 1].height = calHeight
        } else if (this.operation === 'resizing') {
          const index = this.selectedFile.rectangles.findIndex(
            function(ele) {
              return ele.id === this.resizingRectangleId
            }.bind(this)
          )

          if (this.resizeTarget === 'tl') {
            console.log(this.selectedFile.rectangles[index].width)
            console.log(movementX)
            if (this.selectedFile.rectangles[index].x + movementX < 0) {
              this.selectedFile.rectangles[index].x = 0
            } else if (
              this.selectedFile.rectangles[index].width - movementX <
              30
            ) {
              this.selectedFile.rectangles[index].width = 30
            } else {
              this.selectedFile.rectangles[index].x =
                this.selectedFile.rectangles[index].x + movementX
              this.selectedFile.rectangles[index].width =
                this.selectedFile.rectangles[index].width - movementX
            }

            if (this.selectedFile.rectangles[index].y + movementY < 0) {
              this.selectedFile.rectangles[index].y = 0
            } else if (
              this.selectedFile.rectangles[index].height - movementY <
              30
            ) {
              this.selectedFile.rectangles[index].height = 30
            } else {
              this.selectedFile.rectangles[index].y =
                this.selectedFile.rectangles[index].y + movementY
              this.selectedFile.rectangles[index].height =
                this.selectedFile.rectangles[index].height - movementY
            }
          } else if (this.resizeTarget === 'bl') {
            if (this.selectedFile.rectangles[index].x + movementX < 0) {
              this.selectedFile.rectangles[index].x = 0
            } else if (
              this.selectedFile.rectangles[index].width - movementX <
              30
            ) {
              this.selectedFile.rectangles[index].width = 30
            } else {
              this.selectedFile.rectangles[index].x =
                this.selectedFile.rectangles[index].x + movementX
              this.selectedFile.rectangles[index].width =
                this.selectedFile.rectangles[index].width - movementX
            }

            if (this.selectedFile.rectangles[index].height + movementY < 30) {
              this.selectedFile.rectangles[index].height = 30
            } else {
              this.selectedFile.rectangles[index].height =
                this.selectedFile.rectangles[index].height + movementY
            }
          } else if (this.resizeTarget === 'br') {
            if (this.selectedFile.rectangles[index].width + movementX < 30) {
              this.selectedFile.rectangles[index].width = 30
            } else {
              this.selectedFile.rectangles[index].width =
                this.selectedFile.rectangles[index].width + movementX
            }

            if (this.selectedFile.rectangles[index].height + movementY < 30) {
              this.selectedFile.rectangles[index].height = 30
            } else {
              this.selectedFile.rectangles[index].height =
                this.selectedFile.rectangles[index].height + movementY
            }
          }
        }

        event.cancelBubble = true
        this.previousEvent = event
        // return false;
        // }
        // begin 鼠标变化
        const rectangles = this.selectedFile.rectangles
        for (var i = 0; i < rectangles.length; i++) {
          if (
            (this.cursorRect = this.checkClickIsResizeRectangle(rectangles[i], {
              x: event.offsetX,
              y: event.offsetY
            }))
          ) {
            break
          } else if (
            this.checkClickInsideRectangle(rectangles[i], {
              x: event.offsetX,
              y: event.offsetY
            })
          ) {
            this.cursorRect = 'moving'
            break
          }
        }
        // over
      } else if (this.currentTool === 'noose') {
        if (this.operation === 'moving') {
          const path = this.selectedFile.points[movePointId]
          console.log('tem0' + tempath[0].x)
          for (var j = 0; j < path.length; ++j) {
            path[j].x = tempath[j].x + event.offsetX - startX
            path[j].y = tempath[j].y + event.offsetY - startY
            console.log('offsetX' + event.offsetX)
            console.log('startX' + startX)
          }
        } else {
          const points = this.selectedFile.points
          if (points.length > 0) {
            const path = points[points.length - 1]
            if (!path[path.length - 1].closePath) {
              // 最后一个无关闭
              this.drawDashed(
                path[path.length - 1].x,
                path[path.length - 1].y,
                event.offsetX,
                event.offsetY
              )
            }
          }
        }
      }
    },

    onMouseUp: function() {
      if (istouch) {
        istouch = false // 缩放结束
      }
      if (this.currentTool === 'brush') {
        if (mousePressed) {
          this.isShowBrushSize = true
          if (this.isMobile) {
            const canvas = document.getElementById('upper-canvas')
            const context = canvas.getContext('2d')
            const width = canvas.getAttribute('width')
            const height = canvas.getAttribute('height')
            context.clearRect(0, 0, width, height)
          }
          // mousePressed = false;
          // let brushPath = this.selectedFile.brushPath;
          // if (brushPath[brushPath.length - 1].length < 2) {
          //   brushPath.pop(); //点一点要移除
          // } else {
          this.historyPush('brush')
          // }
        }
      } else if (this.currentTool === 'eraser') {
        if (mousePressed) {
          this.isShowBrushSize = true
          // mousePressed = false;
          this.historyPush('eraser')
        }
      } else if (this.currentTool === 'addRectangle') {
        if (this.operation === 'deleting') {
          const index = this.selectedFile.rectangles.findIndex(
            function(ele) {
              return ele.id === this.resizingRectangleId
            }.bind(this)
          )

          this.selectedFile.rectangles.splice(index, 1)
          if (this.selectedFile.rectangles.length === 0) {
            this.cursorRect = null
          }
        } else if (this.operation === 'creating') {
          var length = this.selectedFile.rectangles.length
          if (
            this.selectedFile.rectangles[length - 1].width < 2 ||
            this.selectedFile.rectangles[length - 1].height < 2
          ) {
            this.selectedFile.rectangles.pop()
          }
        }
        this.resizingRectangleId = null
        this.movingRectangleId = null
        this.operation = null
        this.historyPush('addRectangle')
      } else if (this.currentTool === 'noose') {
        const canvas = document.getElementById('upper-canvas') // 清空虚线
        const context = canvas.getContext('2d')
        const width = canvas.getAttribute('width')
        const height = canvas.getAttribute('height')
        context.clearRect(0, 0, width, height)
        this.operation = null
        this.historyPush('noose')
      }
      mousePressed = false
    },
    onMouseLeave: function() {
      if (this.currentTool === 'brush') {
        const canvas = document.getElementById('upper-canvas')
        const context = canvas.getContext('2d')
        const width = canvas.getAttribute('width')
        const height = canvas.getAttribute('height')
        context.clearRect(0, 0, width, height)
        // mousePressed = false;
      }
      if (this.currentTool === 'noose') {
        const canvas = document.getElementById('upper-canvas')
        const context = canvas.getContext('2d')
        const width = canvas.getAttribute('width')
        const height = canvas.getAttribute('height')
        context.clearRect(0, 0, width, height)
      }
      // this.operation = null;
      // mousePressed = false;
    },

    wrapDown: function(e) {
      if (this.currentTool === 'move') {
        mousePressed = true
        startX = e.clientX
        startY = e.clientY

        const str = this.$refs['item'].style.transform

        if (str.indexOf('translate3d') > -1) {
          transX = parseFloat(
            str.substring(str.indexOf('translate3d(') + 12, str.indexOf('px'))
          )
          transY = parseFloat(
            str.substring(str.indexOf('px,') + 4, str.lastIndexOf('px,'))
          )
        }
      }
    },
    wrapMove: function(e) {
      if (this.currentTool === 'move' && mousePressed) {
        this.$refs['preview-wrapper'].style.cursor = 'grab'
        var endX = e.clientX
        var moveX = (endX - startX) / Number(this.zoomLevel) + transX
        var endY = e.clientY
        var moveY = (endY - startY) / Number(this.zoomLevel) + transY

        this.setTransform(this.zoomLevel, moveX, moveY, false)
      }
    },
    wrapUp: function() {
      if (mousePressed) {
        this.historyPush('brush')
        if (this.currentTool === 'brush') {
          this.isShowBrushSize = true
        }
      }
      if (this.currentTool === 'move') {
        this.$refs['preview-wrapper'].style.cursor = 'unset'
      }
      this.operation = null
      mousePressed = false
    },
    wrapLeave: function() {
      if (mousePressed) {
        this.historyPush('brush')
        if (this.currentTool === 'brush') {
          this.isShowBrushSize = true
        }
      }
      if (this.currentTool === 'move') {
        this.$refs['preview-wrapper'].style.cursor = 'unset'
      }
      this.operation = null
      mousePressed = false
    },
    wrapWheel: function(e) {
      let delta = 1
      if (e.deltaY) {
        delta = e.deltaY > 0 ? 1 : -1
      } else if (e.wheelDelta) {
        delta = -e.wheelDelta / 120
      } else if (e.detail) {
        delta = e.detail > 0 ? 1 : -1
      }
      const zoom = (Number(this.zoomLevel) + -delta * 0.1).toFixed(1)
      if (zoom > 0 && zoom < 4.1) {
        this.zoomLevel = zoom
        this.setTransform(this.zoomLevel, 0, 0, true)
      }
    },
    changeSize(val) {
      if (val !== this.preBrushSize) {
        const canvas = document.getElementById('upper-canvas')
        // const context = canvas.getContext("2d");
        const width = canvas.getAttribute('width')
        const height = canvas.getAttribute('height')
        this.drawCursor(width / 2, height / 2)
        this.brushChange = true
      }
      this.preBrushSize = val
    },
    changeSizeOver() {
      this.brushChange = false
    },
    drawCursor(x, y) {
      const canvas = document.getElementById('upper-canvas')
      const context = canvas.getContext('2d')
      const width = canvas.getAttribute('width')
      const height = canvas.getAttribute('height')
      context.clearRect(0, 0, width, height)
      context.beginPath()
      context.lineWidth = 2
      context.strokeStyle = '#FFFFFF'
      if (this.currentTool === 'brush') {
        context.strokeStyle = '#FFFFFF'
      } else {
        context.strokeStyle = '#5555FF'
      }
      // context.shadowOffsetX = 0; // 阴影Y轴偏移
      // context.shadowOffsetY = 2; // 阴影X轴偏移
      // context.shadowBlur = 5; // 模糊尺寸
      // context.shadowColor = "rgba(0, 0, 0, 0.5)"; // 颜色
      // context.fillStyle = "rgba(107, 107, 107, 0.75)";
      context.arc(x, y, this.brushSize / 2, 0, 2 * Math.PI)
      context.stroke()
      if (this.currentTool === 'brush') {
        context.fillStyle = 'rgba(85, 85, 255, 0.6)'
      } else {
        context.fillStyle = 'rgba(255, 255, 255, 0.8)'
      }
      context.fill()
      context.closePath()
    },
    drawDashed(pointx, pointy, x, y) {
      const canvas = document.getElementById('upper-canvas')
      const context = canvas.getContext('2d')
      const width = canvas.getAttribute('width')
      const height = canvas.getAttribute('height')
      context.clearRect(0, 0, width, height)
      context.beginPath()
      context.setLineDash([3, 3])
      context.strokeStyle = '#5555FF'
      context.moveTo(pointx, pointy)
      context.lineTo(x, y)
      context.stroke()
      context.setLineDash([])
    },
    drawBrush() {
      const canvas = document.getElementById('canvas')
      const context = canvas.getContext('2d')
      // let width = canvas.getAttribute("width");
      // let height = canvas.getAttribute("height");

      // const tempCanvas = document.createElement("canvas");
      // const tempCtx = tempCanvas.getContext("2d");
      // tempCanvas.width = width;
      // tempCanvas.height = height;

      const brushPath = this.selectedFile.brushPath
      if (brushPath.length < 1) {
        return
      }
      for (var i = 0; i < brushPath.length; ++i) {
        const path = brushPath[i]
        context.beginPath()

        if (path.length === 1) {
          context.lineWidth = 1
          context.strokeStyle = '#5555FF'
          context.arc(path[0].x, path[0].y, path[0].size / 2, 0, 2 * Math.PI)
          context.stroke()
          context.fillStyle = '#5555FF'
          context.fill()
        } else {
          context.lineWidth = path[0].size
          context.lineCap = 'round'
          context.lineJoin = 'round'
          // tempCanvas.style.opacity="0.4";
          context.strokeStyle = '#5555FF'
          context.moveTo(path[0].x, path[0].y)
          for (var j = 1; j < path.length; ++j) { context.lineTo(path[j].x, path[j].y) }
          context.stroke()
        }
      }

      // context.drawImage(tempCanvas, 0, 0); // 将缓存 canvas 复制到旧的 canvas
    },
    drawEraser() {
      const canvas = document.getElementById('canvas')
      const context = canvas.getContext('2d')

      const eraserPath = this.selectedFile.eraserPath
      if (eraserPath.length < 1) {
        return
      }
      for (let i = 0; i < eraserPath.length; ++i) {
        const path = eraserPath[i]
        for (let j = 0; j < path.length; ++j) {
          context.save()
          context.beginPath()
          context.arc(path[j].x, path[j].y, path[0].size / 2, 0, Math.PI * 2)
          context.clip()
          context.clearRect(
            path[j].x - path[0].size / 2,
            path[j].y - path[0].size / 2,
            path[0].size,
            path[0].size
          )
          context.restore()
        }
      }
    },
    historyPush(type, resource_id, num) {
      this.undoOperate = true
      this.redoOperate = false

      let numfile // 批量去水印时需要指定某个文件
      if (resource_id) {
        const index = this.uploadQueue.findIndex(function(ele) {
          return ele.resource_id === resource_id
        })
        numfile = this.uploadQueue[index]
      } else {
        numfile = this.selectedFile
      }
      numfile.hStep++
      if (numfile.hStep < numfile.historyArray.length) {
        numfile.historyArray.length = numfile.hStep
      }
      // url: document.getElementById('canvas').toDataURL(),
      numfile.historyArray.push({
        rectangles: JSON.parse(JSON.stringify(numfile.rectangles)),
        points: JSON.parse(JSON.stringify(numfile.points)),
        brushPath: JSON.parse(JSON.stringify(numfile.brushPath)),
        eraserPath: JSON.parse(JSON.stringify(numfile.eraserPath)),
        processed_url: numfile.processed_url,
        resource_id: numfile.resource_id
      })
    },
    undo() {
      if (!this.undoOperate) {
        return
      }
      if (this.selectedFile.hStep === 0) {
        this.undoOperate = false
        this.redoOperate = true
        this.selectedFile.hStep--
        this.selectedFile.rectangles = []
        this.selectedFile.points = []
        this.selectedFile.brushPath = []
        this.selectedFile.eraserPath = []
        this.selectedFile.processed_url = this.selectedFile.processed_url2
        this.selectedFile.resource_id = this.selectedFile.resource_id2
      } else if (this.selectedFile.hStep > 0) {
        this.undoOperate = true
        this.redoOperate = true
        this.selectedFile.hStep--

        this.selectedFile.rectangles = JSON.parse(
          JSON.stringify(
            this.selectedFile.historyArray[this.selectedFile.hStep].rectangles
          )
        )
        this.selectedFile.points = JSON.parse(
          JSON.stringify(
            this.selectedFile.historyArray[this.selectedFile.hStep].points
          )
        )
        this.selectedFile.brushPath = JSON.parse(
          JSON.stringify(
            this.selectedFile.historyArray[this.selectedFile.hStep].brushPath
          )
        )
        this.selectedFile.eraserPath = JSON.parse(
          JSON.stringify(
            this.selectedFile.historyArray[this.selectedFile.hStep].eraserPath
          )
        )
        this.selectedFile.processed_url = JSON.parse(
          JSON.stringify(
            this.selectedFile.historyArray[this.selectedFile.hStep]
              .processed_url
          )
        )
        this.selectedFile.resource_id = JSON.parse(
          JSON.stringify(
            this.selectedFile.historyArray[this.selectedFile.hStep].resource_id
          )
        )
      }
      if (!this.uploadQueue[0].processed_url) {
        this.downloadNum = 0
      }
    },
    redo() {
      if (!this.redoOperate) {
        return
      }
      if (this.selectedFile.hStep < this.selectedFile.historyArray.length - 1) {
        this.undoOperate = true
        this.redoOperate = true
        this.selectedFile.hStep++

        if (
          this.selectedFile.hStep ===
          this.selectedFile.historyArray.length - 1
        ) {
          this.redoOperate = false
          // this.selectedFile.hStep--;
        }
      } else {
        // this.redoOperate = false
      }
      this.selectedFile.rectangles = JSON.parse(
        JSON.stringify(
          this.selectedFile.historyArray[this.selectedFile.hStep].rectangles
        )
      )
      this.selectedFile.points = JSON.parse(
        JSON.stringify(
          this.selectedFile.historyArray[this.selectedFile.hStep].points
        )
      )
      this.selectedFile.brushPath = JSON.parse(
        JSON.stringify(
          this.selectedFile.historyArray[this.selectedFile.hStep].brushPath
        )
      )
      this.selectedFile.eraserPath = JSON.parse(
        JSON.stringify(
          this.selectedFile.historyArray[this.selectedFile.hStep].eraserPath
        )
      )
      this.selectedFile.processed_url = JSON.parse(
        JSON.stringify(
          this.selectedFile.historyArray[this.selectedFile.hStep].processed_url
        )
      )
      this.selectedFile.resource_id = JSON.parse(
        JSON.stringify(
          this.selectedFile.historyArray[this.selectedFile.hStep].resource_id
        )
      )
      if (this.uploadQueue[0].processed_url) {
        this.downloadNum = 1
      }
    },
    // applyToAll: function () {
    //   for (let i = 0; i < this.uploadQueue.length; i++) {
    //     this.selectedFile.rectangles.find(
    //       function (ele) {
    //         return ele.id === this.applyingToOthersRectangleId;
    //       }.bind(this)
    //     ).applied = true;
    //     if (this.uploadQueue[i].resource_id !== this.selectedFile.resource_id) {
    //       let index = this.uploadQueue[i].rectangles.findIndex(
    //         function (ele) {
    //           return ele.id === this.applyingToOthersRectangleId;
    //         }.bind(this)
    //       );
    //       if (index > -1) {
    //         this.uploadQueue[i].rectangles[
    //           index
    //         ].x = this.selectedFile.rectangles[
    //           this.applyingToOthersRectangleId
    //         ].x;
    //         this.uploadQueue[i].rectangles[
    //           index
    //         ].y = this.selectedFile.rectangles[
    //           this.applyingToOthersRectangleId
    //         ].y;
    //         this.uploadQueue[i].rectangles[
    //           index
    //         ].width = this.selectedFile.rectangles[
    //           this.applyingToOthersRectangleId
    //         ].width;
    //         this.uploadQueue[i].rectangles[
    //           index
    //         ].height = this.selectedFile.rectangles[
    //           this.applyingToOthersRectangleId
    //         ].height;
    //       } else {
    //         this.uploadQueue[i].rectangles.push({
    //           id: this.uploadQueue[i].rectangles.length,
    //           x: this.selectedFile.rectangles[this.applyingToOthersRectangleId]
    //             .x,
    //           y: this.selectedFile.rectangles[this.applyingToOthersRectangleId]
    //             .y,
    //           width: this.selectedFile.rectangles[
    //             this.applyingToOthersRectangleId
    //           ].width,
    //           height: this.selectedFile.rectangles[
    //             this.applyingToOthersRectangleId
    //           ].height,
    //           applied: true,
    //           isHidden: false,
    //         });
    //       }
    //     }
    //     this.uploadQueue[i].touched = true;
    //   }
    //   this.showConfirm = false;
    // },

    reDraw: async function() {
      const canvas = document.getElementById('canvas')
      if (canvas && this.selectedFile) {
        const context = canvas.getContext('2d')
        const width = canvas.getAttribute('width')
        const height = canvas.getAttribute('height')
        // 清空画布
        context.clearRect(0, 0, width, height)
        // 绘制画笔
        this.drawBrush()
        // 绘制锁套
        this.drawNoose()
        // 橡皮擦
        // this.drawEraser();
        // 绘制水印框
        var rectangles = this.selectedFile.rectangles
        for (var i = 0; i < rectangles.length; i++) {
          this.drawRectangle(rectangles[i])
        }
      }
    },
    drawNoose() {
      var points = this.selectedFile.points
      if (points.length < 1) {
        return
      }
      const canvas = document.getElementById('canvas')
      const ctx = canvas.getContext('2d')

      for (var i = 0; i < points.length; ++i) {
        var path = points[i]

        // if (path.length<1)
        //     continue;

        ctx.beginPath()
        ctx.lineWidth = 2
        ctx.setLineDash([3, 3])
        ctx.strokeStyle = '#5555FF'
        ctx.moveTo(path[0].x, path[0].y)

        for (var j = 1; j < path.length; ++j) ctx.lineTo(path[j].x, path[j].y)

        ctx.stroke()

        // 画圆// !path[path.length - 1].hasOwnProperty("closePath")
        if (!path[path.length - 1].closePath) {
          ctx.beginPath()
          ctx.setLineDash([])
          ctx.arc(path[0].x, path[0].y, 5, 0, Math.PI * 2)
          ctx.fillStyle = '#5555FF'
          ctx.fill()
          ctx.closePath()
          ctx.stroke()
        } else {
          ctx.fillStyle = '#5555FF' // 形成蒙版
          ctx.fill()
        }
      }
    },
    drawRectangle: function(rectangle) {
      //

      const canvas = document.getElementById('canvas')
      const context = canvas.getContext('2d')

      context.lineWidth = 2
      context.strokeStyle = 'white'
      context.beginPath()
      context.setLineDash([3, 3])
      context.moveTo(rectangle.x, rectangle.y)
      context.lineTo(rectangle.x + rectangle.width, rectangle.y)
      context.lineTo(
        rectangle.x + rectangle.width,
        rectangle.y + rectangle.height
      )
      context.lineTo(rectangle.x, rectangle.y + rectangle.height)
      context.lineTo(rectangle.x, rectangle.y)
      context.stroke()
      context.setLineDash([])
      context.fillStyle = 'rgba(85, 85, 255, 1)'
      context.fillRect(
        rectangle.x,
        rectangle.y,
        rectangle.width,
        rectangle.height
      )
      if (rectangle.width > 20 && rectangle.height > 20) {
        if (
          this.resizingRectangleId !== rectangle.id ||
          this.resizeTarget !== 'tl'
        ) {
          context.drawImage(top_left, rectangle.x - 1, rectangle.y - 1, 20, 20)
        }

        if (
          this.resizingRectangleId !== rectangle.id ||
          this.resizeTarget !== 'bl'
        ) {
          context.drawImage(
            bottom_left,
            rectangle.x - 1,
            rectangle.y + rectangle.height - 20 + 1,
            20,
            20
          )
        }

        if (
          this.resizingRectangleId !== rectangle.id ||
          this.resizeTarget !== 'br'
        ) {
          context.drawImage(
            bottom_right,
            rectangle.x + rectangle.width - 20 + 1,
            rectangle.y + rectangle.height - 20 + 1,
            20,
            20
          )
        }

        context.drawImage(
          top_right,
          rectangle.x + rectangle.width - 20 + 1,
          rectangle.y - 1,
          20,
          20
        )
      }
      if (rectangle.width > 1 && rectangle.height > 1) {
        context.drawImage(
          closeIconImage,
          rectangle.x + rectangle.width - 18,
          rectangle.y + 2,
          16,
          16
        )
      }
      // if (
      //   this.resizingRectangleId === rectangle.id &&
      //   this.operation === "resizing"
      // ) {
      // if (this.resizeTarget === "tl") {
      //   context.drawImage(arrowB, rectangle.x - 11, rectangle.y - 11, 22, 22);
      // }
      // else if (this.resizeTarget === "bl") {
      //   context.drawImage(
      //     arrowA,
      //     rectangle.x - 11,
      //     rectangle.y - 11 + rectangle.height,
      //     22,
      //     22
      //   );
      // }
      // else if (this.resizeTarget === "br") {
      //   context.drawImage(
      //     arrowB,
      //     rectangle.x + rectangle.width - 11,
      //     rectangle.y - 11 + rectangle.height,
      //     22,
      //     22
      //   );
      // }
      // }
      // else if (
      //   this.movingRectangleId === rectangle.id &&
      //   this.operation === "moving"
      // ) {
      //   context.drawImage(
      //     moveIcon,
      //     rectangle.x + rectangle.width / 2 - 11,
      //     rectangle.y + rectangle.height / 2 - 11,
      //     22,
      //     22
      //   );
      // }
    },
    isPointInPath: function(path, x, y) {
      const canvas = document.getElementById('canvas')
      const width = canvas.getAttribute('width')
      const height = canvas.getAttribute('height')

      const tempCanvas = document.createElement('canvas')
      const tempCtx = tempCanvas.getContext('2d')
      tempCanvas.width = width
      tempCanvas.height = height

      tempCtx.beginPath()
      tempCtx.moveTo(path[0].x, path[0].y)
      for (var j = 1; j < path.length; ++j) { tempCtx.lineTo(path[j].x, path[j].y) }
      tempCtx.stroke()
      return tempCtx.isPointInPath(x, y)
    },
    checkClickInsideRectangle: function(rectangle, click) {
      return (
        click.x > rectangle.x + this.padding &&
        click.x < rectangle.x + rectangle.width - this.padding &&
        click.y > rectangle.y + this.padding &&
        click.y < rectangle.y + rectangle.height - this.padding
      )
    },

    checkClickIsResizeRectangle: function(rectangle, click) {
      if (
        this.distance(
          {
            x: rectangle.x,
            y: rectangle.y
          },
          click
        ) < this.padding
      ) {
        return 'tl'
      } else if (
        this.distance(
          {
            x: rectangle.x + rectangle.width - 10,
            y: rectangle.y + 10
          },
          click
        ) < 13
      ) {
        return 'tr'
      } else if (
        this.distance(
          {
            x: rectangle.x,
            y: rectangle.y + rectangle.height
          },
          click
        ) < this.padding
      ) {
        return 'bl'
      } else if (
        this.distance(
          {
            x: rectangle.x + rectangle.width,
            y: rectangle.y + rectangle.height
          },
          click
        ) < this.padding
      ) {
        return 'br'
      } else {
        return false
      }
    },

    checkClickIsAppliedToOthers: function(rectangle, click) {
      if (
        this.distance(
          {
            x: rectangle.x + rectangle.width,
            y: rectangle.y + rectangle.height / 2
          },
          click
        ) < this.padding
      ) {
        return true
      } else {
        return false
      }
    },

    distance: function(coordA, coordB) {
      return Math.sqrt(
        (coordA.x - coordB.x) * (coordA.x - coordB.x) +
          (coordA.y - coordB.y) * (coordA.y - coordB.y)
      )
    },

    // 下载完成的文件
    downloadFinished: function() {
      if (!this.isLogined) {
        this.showAccountDialog()
        return
      }
      this.downloadNum = 0
      const arrtemp = []
      for (let i = 0; i < this.uploadQueue.length; i++) {
        if (
          this.uploadQueue[i].status === 'finished' &&
          this.uploadQueue[i].processed_url
        ) {
          // setTimeout(() => {
          //   this.downloadLink(
          //     this.uploadQueue[i].processed_url,
          //     this.uploadQueue[i].name
          //   );
          // }, i * 500);
          arrtemp.push(i)

          this.downloadNum++
          this.appStatus = 'editing'
        }
      }
      if (this.downloadNum === 0) {
        return
      } else {
        this.modalappdownload(arrtemp)
      }
    },
    modalappdownload: function(arrtemp) {
      this.processNum = 1
      this.modalAppStatus = 'download'
      this.showModalApp = true
      // if (isMac) {
      //   this.$nextTick(function () {
      //     this.$refs.pcItem.style.display = "none";
      // this.$refs.pcItem.nextElementSibling.style.marginLeft="7%"
      //   });
      // }
      const bartimer = window.setInterval(() => {
        this.processNum = parseInt(this.processNum) + 1
        this.$refs.processWidth.style.width = this.processNum + '%'
        if (this.processNum === 99) {
          window.clearInterval(bartimer)
        }
      }, 50)
      for (let i = 0; i < arrtemp.length; i++) {
        setTimeout(() => {
          window.clearInterval(bartimer)
          this.downloadLink(
            this.uploadQueue[arrtemp[i]].processed_url,
            this.uploadQueue[arrtemp[i]].name
          )
          this.processNum = 100
          this.$refs.processWidth.style.width = this.processNum + '%'
          this.modalAppStatus = 'finish'
        }, 5000 + i * 500)
      }
    },

    // downloadByBlob(url, name) {
    //   this.downloadLink(url, name);
    // if (this.isMobile) {
    //   this.downloadLink(url, name);
    // } else {
    //   let image = new Image();
    //   image.setAttribute("crossOrigin", "anonymous");
    //   image.src = url;

    //   image.onload = () => {
    //     let canvas = document.createElement("canvas");
    //     canvas.width = image.width;
    //     canvas.height = image.height;
    //     let ctx = canvas.getContext("2d");
    //     ctx.drawImage(image, 0, 0, image.width, image.height);
    //     //移动端不支持blob下载
    //     // let url = canvas.toDataURL();
    //     // this.downloadLink(url, name);
    //     canvas.toBlob((blob) => {
    //       let url = URL.createObjectURL(blob);
    //       this.downloadLink(url, name);
    //       // 用完释放URL对象
    //       URL.revokeObjectURL(url);
    //     });
    //   };
    // }
    // },
    downloadLink(link, fileName) {
      if (this.isMobile) {
        if (document.documentElement.scrollTop) {
          document.documentElement.scrollTop = 0
        }
        if (document.body.scrollTop) {
          document.body.scrollTop = 0
        }
        this.mobileImgDownload = true
        this.showModalApp = false
        return
      }
      var anchor = document.createElement('a')
      anchor.id = 'linkAnchor'
      anchor.href = link
      if (fileName) {
        anchor.download = fileName
      }
      document.body.appendChild(anchor)
      anchor.click()
      anchor = null
      var anchorEle = document.getElementById('linkAnchor')
      document.body.removeChild(anchorEle)
    },
    // --------------------------------------------- 提交任务开始

    modalappdoing: function(arrtemp) {
      this.processNum = 1
      this.modalAppStatus = 'upload'
      this.showModalApp = true
      if (isMac) {
        this.$nextTick(function() {
          this.$refs.pcItem.style.display = 'none'
          // this.$refs.pcItem.nextElementSibling.style.marginLeft="7%"
        })
      }
      const bartimer = window.setInterval(() => {
        this.processNum = parseInt(this.processNum) + 1
        this.$refs.processWidth.style.width = this.processNum + '%'
        if (this.processNum === 90) {
          window.clearInterval(bartimer)
        }
      }, 55)
      setTimeout(() => {
        window.clearInterval(bartimer)
        for (let i = 0; i < arrtemp.length; i++) {
          this.submitSingleTask(this.uploadQueue[arrtemp[i]])
        }
        // this.submitSingleTask(isResubmit)
        bartimer90 = window.setInterval(() => {
          this.processNum = parseInt(this.processNum) + 1
          this.$refs.processWidth.style.width = this.processNum + '%'
          if (this.$refs.processWidth.style.width === '99%') {
            window.clearInterval(bartimer90)
          }
        }, 200)
      }, 5000)
    },
    submit: async function(isResubmit) {
      // let arrtemp = []
      this.processedNumber = 0
      for (let i = 0; i < this.uploadQueue.length; i++) {
        if (isResubmit) {
          // 只重提失败任务
          if (this.uploadQueue[i].status === 'failed') {
            // if(this.isMobile){
            setTimeout(() => {
              this.submitSingleTask(this.uploadQueue[i])
            }, 600 * i)
            // }else{
            //   arrtemp.push(i)
            // }
            this.processedNumber++
          }
        } else {
          // 只提交操作过的文件
          const points = this.uploadQueue[i].points
          if (
            this.uploadQueue[i].touched &&
            (this.uploadQueue[i].brushPath.length !== 0 ||
              (points.length > 0 &&
                points[points.length - 1][points[points.length - 1].length - 1]
                  .closePath) ||
              this.uploadQueue[i].rectangles.length !== 0)
          ) {
            setTimeout(() => {
              // qps：1s2个，1分钟10个
              this.submitSingleTask(this.uploadQueue[i])
            }, 600 * i)
            // }else{
            //   arrtemp.push(i)
            // }
            this.processedNumber++
          }
        }
      }

      if (this.processedNumber === 0) {
        this.modalMsg = '请选择需要去除水印的区域！'
        this.somethingError = true
        return
      }
      // else{
      //   if(!this.isMobile){
      //     this.modalappdoing(arrtemp)
      //   }
      // }
      // if(this.isMobile){
      this.appStatus = 'processing'
      // }
      this.processedSuccessNumber = 0
      this.processedFailNumber = 0
    },
    // 预加载图片，最后返回一个promise对象
    loadImage(url) {
      return new Promise((resolve) => {
        const img = new Image()
        img.setAttribute('crossOrigin', 'anonymous')
        img.onload = () => resolve(img)
        img.src = url
      })
    },

    imgToFile(imgurl) {
      return new Promise((resolve) => {
        console.log(imgurl)
        const image = new Image()
        image.src = imgurl
        image.setAttribute('crossOrigin', 'Anonymous')
        image.onload = function() {
          const base64 = getBase64Image(image)
          const file = btof(base64, 'test')
          console.log(file)
          resolve(file)
        }
      })
    },

    uploadOss: async function(file) {
      const maskfilename = 'mask.png'
      const authentications = await this.refreshAccess(maskfilename)
      return new Promise((resolve, reject) => {
        // const extension = ".png";
        const key = authentications.objects[maskfilename]
        const url = authentications['callback']['url']
        const callbackBody = authentications['callback']['body']
        const callback = {
          url: url,
          body: callbackBody.replace('${filename}', encodeURI(maskfilename))
        }
        this.client
          .multipartUpload(key, file, {
            cancelFlag: true,
            callback: callback,
            progress: this.onProgress,
            partSize: 500 * 1024,
            headers: {
              'Content-Disposition': encodeURI(maskfilename)
            }
          })
          .then(
            function(res) {
              if (res.data.status === 200) {
                resolve(res.data.data.resource_id)
              } else {
                reject('upload_fail')
              }
            }
          )
          .catch((err) => {
            console.log(err)
            reject('upload_fail')
          })
      })
    },
    // 提交单个任务
    submitSingleTask: async function(resource) {
      this.currentDisplayProcessFile = JSON.parse(JSON.stringify(resource))

      var ratio
      if (resource.width < resource.afterWidth) {
        ratio = 1
      } else {
        ratio = resource.afterWidth / resource.width
      }

      const canvasCopy = document.createElement('canvas')
      const context = canvasCopy.getContext('2d')
      canvasCopy.width = resource.width
      canvasCopy.height = resource.height
      context.fillStyle = 'black'
      context.fillRect(0, 0, resource.width, resource.height)
      // 将 套索 加入画布
      var points = resource.points
      if (points.length > 0) {
        context.save()
        context.beginPath()
        for (var i = 0; i < points.length; ++i) {
          var path = points[i]
          if (path.length > 2) {
            context.moveTo(path[0].x / ratio, path[0].y / ratio)
            for (var j = 1; j < path.length; ++j) { context.lineTo(path[j].x / ratio, path[j].y / ratio) }
          }
        }
        context.closePath()
        context.clip()
        context.fillStyle = 'white'
        context.fillRect(0, 0, resource.width, resource.height)
        context.restore()
      }
      // 将 画笔 加入画布
      var brushPath = resource.brushPath
      for (let i = 0; i < brushPath.length; ++i) {
        const path = brushPath[i]
        context.beginPath()
        if (path.length === 1) {
          context.lineWidth = 1
          context.strokeStyle = 'white'
          context.arc(
            path[0].x / ratio,
            path[0].y / ratio,
            path[0].size / ratio / 2,
            0,
            2 * Math.PI
          )
          context.stroke()
          context.fillStyle = 'white'
          context.fill()
        } else {
          context.lineWidth = path[0].size / ratio
          context.lineCap = 'round'
          context.lineJoin = 'round'
          context.strokeStyle = 'white'
          context.moveTo(path[0].x / ratio, path[0].y / ratio)
          for (let j = 1; j < path.length; ++j) { context.lineTo(path[j].x / ratio, path[j].y / ratio) }

          context.stroke()
        }
      }
      // 将 橡皮擦 加入画布
      var eraserPath = resource.eraserPath
      for (let i = 0; i < eraserPath.length; ++i) {
        const path = eraserPath[i]
        for (let j = 0; j < path.length; ++j) {
          context.save()
          context.beginPath()
          context.arc(path[j].x, path[j].y, path[j].size / 2, 0, Math.PI * 2)
          context.clip()
          context.clearRect(
            path[j].x - path[j].size / 2,
            path[j].y - path[j].size / 2,
            path[j].size,
            path[j].size
          )
          context.restore()
        }
      }
      // 将 矩形 加入画布
      context.fillStyle = 'white'
      var rectangles = resource.rectangles.filter(function(ele) {
        return !ele.isHidden
      })
      for (let i = 0; i < rectangles.length; i++) {
        context.fillRect(
          Math.floor(rectangles[i].x / ratio),
          Math.floor(rectangles[i].y / ratio),
          Math.floor(rectangles[i].width / ratio),
          Math.floor(rectangles[i].height / ratio)
        )
      }

      // 将画布内容导出
      // let mask_base64 = canvasCopy.toDataURL("image/png");
      // mask_base64 = mask_base64.substring(mask_base64.indexOf(",") + 1);
      // 封装blob对象
      // let blob = dataURItoBlob(mask_base64);
      // let file = blob;
      // let mask_resource_id = await this.uploadOss(file)
    },

    // --------------------------------------------- 提交任务结束
    // --------------------------------------------- 拖拽开始
    bodyAddDragenter() {
      // 判断文件是否被拖拽进页面
      const bodyEl = document.querySelector('body')
      const _this = this
      bodyEl.addEventListener('dragenter', function(e) {
        e.preventDefault()
        const appStatus = _this.appStatus
        if (
          e.dataTransfer.types[0] === 'Files' &&
          appStatus !== 'processing' &&
          appStatus !== 'uploading'
        ) {
          _this.changeMast('flex')
        }
      })
    },
    fileDragover(e) {
      // 阻止默认Dragover事件 防止文件直接被浏览器打开
      e.preventDefault()
    },
    fileDragleave(e) {
      e.preventDefault()
      this.changeMast('none')
    },
    fileDrop(e) {
      e.preventDefault()
      const type = [
        'image/jpeg',
        'image/bmp',
        'image/png',
        'image/webp',
        'image/bitmap'
      ]
      const file = e.dataTransfer.files[0]
      !!file &&
        (!!type.find((item) => item === file.type) === true
          ? this.onAddFileChange(file)
          : MessageBox.alert(
            '格式不支持，请转换成JPG、BMP、Webp或PNG！',
            '提示',
            {
              confirmButtonText: '确定',
              center: true,
              showClose: false,
              customClass: 'mask_custom'
            }
          ))
      this.changeMast('none')
    },
    changeMast(attribute) {
      const maskEl = document.querySelector('.mask')
      maskEl.style.display = attribute
    },
    // --------------------------------------------- 文件上传开始
    addFile: function(type, reAddFile) {
      this.resourceType = type
      this.$refs.addFileInput.click()
    },

    onAddFileChange: async function(e) {
      // 清空当前队列
      this.uploadQueue = []
      this.fileList = []
      this.downloadNum = 0
      this.uploaded = 0
      var files = []
      for (let i = 0; i < this.$refs.addFileInput.files.length; i++) {
        files.push(this.$refs.addFileInput.files[i])
      }
      !!e && (this.resourceType = 'image')
      !!e && files.push(e)
      console.log(files, this.resourceType)
      this.$refs.addFileInput.files = null
      this.$refs.addFileInput.value = ''
      // if (this.resourceType === "image") {
      //   files = files.filter(
      //     function (ele) {
      //       return this.getFileType(ele.name) === "images";
      //     }.bind(this)
      //   );
      // }

      if (
        this.resourceType === 'image' &&
        files.length + this.uploadQueue.length > 5
      ) {
        this.modalMsg = '最多同时处理5个任务！'
        this.somethingError = true
        return false
      }
      document.getElementById('ap-header').style.display = 'none'
      document.getElementsByTagName('footer')[0].style.display = 'none'
      if (document.getElementsByClassName('talkie-container').length > 0) {
        document.getElementsByClassName('talkie-container')[0].style.display =
          'none'
      }
      if (document.getElementById('chat-widget-container')) {
        document.getElementById('chat-widget-container').style.display = 'none'
      }
      if (document.getElementsByClassName('wechatbox').length > 0) {
        document.getElementsByClassName('wechatbox')[0].style.display = 'none'
      }
      // 批量上传
      this.currentRouter = 'fileList'
      this.appStatus = 'uploading'

      this.currentUploadQueue = []

      for (let i = 0; i < files.length; i++) {
        if (files[i].size === 0) {
          this.modalMsg = '失败，请稍后重试！'
          this.somethingError = true
          this.appStatus = 'editing'
          return
        }
        let quality = 0.8
        if (files[i].size > 10 * 1024 * 1024) {
          quality = ((10 * 1024 * 1024) / files[i].size).toFixed(2)
        }
        const pressFile = await this.compressFile(files[i], quality)
        this.currentUploadQueue.push(pressFile)
      }

      for (let i = 0; i < this.currentUploadQueue.length; i++) {
        this.fileList.push(
          Object.assign(this.currentUploadQueue[i], {
            status: 'uploading',
            progress: 0
          })
        )
        this.uploadSingleFile(this.fileList[this.fileList.length - 1])
      }
    },
    compressFile(file, quality) {
    },
    // 上传单个文件
    uploadSingleFile: async function(file) {
      const authentications = await this.refreshAccess(file.name)
      const key = authentications.objects[file.name]
      file['key'] = key
      this.uploadQueue.push({
        name: file.name,
        resource_id: null,
        resource_id2: null, // 第一次的值防止改变用于撤销为0的值
        task_id: null,
        upload_progress: 0, // 上传进度
        process_progress: 0, // 处理进度
        query_interval: null,
        processed_url: null,
        processed_url2: null, // 第一次的值防止改变用于撤销为0的值
        key: key,
        status: 'uploading',
        url: null,
        type: null,
        width: null,
        height: null,
        afterWidth: null,
        afterHeight: null,
        historyArray: [],
        hStep: -1,
        brushPath: [],
        points: [],
        eraserPath: [],
        rectangles: [],
        touched: false, // 是否已操作过
        image_thumb_url: null
      })
      const url = authentications['callback']['url']
      const callbackBody = authentications['callback']['body']
      const ossfilename = file.name.replace(/;|；|,|，|%/g, '-')
      const callback = {
        url: url,
        body: callbackBody.replace('${filename}', encodeURI(ossfilename))
      }

      this.client
        .multipartUpload(key, file, {
          cancelFlag: true,
          callback: callback,
          progress: this.onProgress,
          partSize: 500 * 1024,
          headers: {
            'Content-Disposition': encodeURI(file.name)
          }
        })
        .then(
          function(res) {
            if (res.data.status === 200) {
              var key = res.name
              let index
              for (let i = 0; i < this.uploadQueue.length; i++) {
                if (this.uploadQueue[i]['key'] === key) {
                  index = i
                }
              }
              if (this.resourceType === 'image') {
                if (index > -1) {
                  // this.uploadQueue[index]["type"] = res.data.data.resource.type;
                  this.uploadQueue[index]['upload_progress'] = 1
                  this.uploadQueue[index]['status'] = 'uploaded'
                  // this.uploadQueue[index]["image_thumb_url"] =
                  // res.data.data.resource.image_thumb_url;
                  this.uploadQueue[index]['url'] = res.data.data.url
                  this.uploadQueue[index]['processed_url2'] = res.data.data.url
                  this.uploadQueue[index]['width'] =
                    res.data.data.file_info.width
                  this.uploadQueue[index]['height'] =
                    res.data.data.file_info.height
                  this.uploadQueue[index]['resource_id'] =
                    res.data.data.resource_id
                  this.uploadQueue[index]['resource_id2'] =
                    res.data.data.resource_id
                  this.uploaded++

                  if (this.uploaded === this.currentUploadQueue.length) {
                    this.appStatus = 'uploaded'
                    this.selectFile(this.uploadQueue[index], true)
                    // test
                    Storage.set(
                      'imgInfo',
                      JSON.parse(JSON.stringify(this.uploadQueue[index]))
                    )
                  }
                }
              }
            }
          }.bind(this)
        )
        .catch((err) => {
          console.log(err)
          this.modalMsg = '失败，请稍后重试！'
          this.somethingError = true
          this.appStatus = 'editing'
        })
    },

    onProgress: function(progress, checkpoint) {
      // res
      if (checkpoint && checkpoint.name) {
        let index
        for (let i = 0; i < this.uploadQueue.length; i++) {
          if (this.uploadQueue[i]['key'] === checkpoint.name) {
            index = i
          }
        }
        if (index > -1) {
          this.uploadQueue[index]['upload_progress'] = progress
          if (progress === 1) {
            this.uploadQueue[index]['status'] = 'uploaded'
          }
        }
      }
    },

    getFileType: function(fileName) {
      var extension = fileName
        .substring(fileName.lastIndexOf('.'))
        .toLowerCase()
      if (
        this.pictureFileExtensions.some(function(ele) {
          return ele === extension
        })
      ) {
        return 'images'
      } else if (
        this.videoFileExtensions.some(function(ele) {
          return ele === extension
        })
      ) {
        return 'videos'
      } else {
        return null
      }
    },

    getShortName: function(fileName, maxLength) {
      if (!fileName) {
        return ''
      }
      const index = fileName.lastIndexOf('.')
      var extension = fileName.substring(index)
      var name = fileName.substr(0, index)
      if (name.length > maxLength - extension.length) {
        return name.substr(0, maxLength - extension.length) + '...' + extension
      } else {
        return fileName
      }
    },

    removeFile: function(file) {
      let index
      for (let i = 0; i < this.uploadQueue.length; i++) {
        if (this.uploadQueue[i]['key'] === file['key']) {
          index = i
        }
      }
      this.uploadQueue.splice(index, 1)

      if (this.uploadQueue.length === 0) {
        const canvas = this.$refs['canvas']
        canvas.setAttribute('width', 0)
        canvas.setAttribute('height', 0)

        const upperCanvas = this.$refs['upper-canvas']
        upperCanvas.setAttribute('width', 0)
        upperCanvas.setAttribute('height', 0)
        this.undoOperate = false
        this.redoOperate = false
        this.selectedFile = null
      } else {
        if (this.selectedFile['key'] === file['key']) {
          this.selectFile(this.uploadQueue[0])
        }
      }
      // 下载变化
      let num = 0
      for (let i = 0; i < this.uploadQueue.length; i++) {
        if (this.uploadQueue[i].status === 'finished') {
          num++
        }
      }
      if (num === 0) {
        this.downloadNum = 0
      }
    },

    refreshAccess: async function(filename) {
      //
    },
    /**
     * @param {*} key  [保存数据的key]
     * @param {*} value [保存数据的值]
     * @param {*} expires [过期的时间，单位：秒]
     */
    saveData(key, value, expires) {
      if (!value) {
        Storage.remove(key)
      } else {
        Storage.set(key, {
          value,
          expires: new Date().getTime() + expires * 1000
        })
      }
    },

    // 获取保存的数据
    getData(key) {
      try {
        const data = Storage.get(key)
        if (!data || data.expires < Date.now()) {
          return null
        } else {
          return data.value
        }
      } catch (e) {
        console.log(e)
        return null
      }
    },

    dragControllerDiv: function() {
      var resize = document.getElementsByClassName('resize')
      var left = document.getElementsByClassName('before')
      var box = document.getElementsByClassName('magicbox')
      for (let i = 0; i < resize.length; i++) {
        resize[i].onmousedown = function(e) {
          var beginX = e.clientX
          resize[i].left = resize[i].offsetLeft
          document.onmousemove = function(e) {
            var overX = e.clientX
            var moveLen = resize[i].left + (overX - beginX)
            var maxT = box[i].clientWidth - resize[i].offsetWidth
            if (moveLen < -19) moveLen = -19 // 左边区域的最小宽度为150px
            if (moveLen > maxT + 19) moveLen = maxT + 19 // 右边区域最小宽度为150px
            resize[i].style.left = moveLen + 19 + 'px' // 设置左侧区域的宽度
            left[i].style.width = moveLen + 19 + 'px'
          }
          // 鼠标松开事件
          document.onmouseup = function() {
            document.onmousemove = null
            document.onmouseup = null
            resize[i].releaseCapture && resize[i].releaseCapture() // 当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          }
          resize[i].setCapture && resize[i].setCapture() // 该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false
        }

        // 移动端
        var isPress = false
        var beginX, overX
        var startBox = function(e) {
          e.stopPropagation()
          isPress = true
          resize[i].left = resize[i].offsetLeft
          if (!e.touches) {
            // 兼容移动端
            beginX = e.clientX
          } else {
            // 兼容PC端
            beginX = e.touches[0].clientX
          }
        }
        var moveBox = function(e) {
          if (isPress) {
            if (!e.touches) {
              // 兼容移动端
              overX = e.clientX
            } else {
              // 兼容PC端
              overX = e.touches[0].clientX
            }

            var moveLen = resize[i].left + (overX - beginX)
            var maxT = box[i].clientWidth - resize[i].offsetWidth
            if (moveLen < -19) moveLen = -19 // 左边区域的最小宽度为150px
            if (moveLen > maxT + 19) moveLen = maxT + 19 // 右边区域最小宽度为150px
            resize[i].style.left = moveLen + 19 + 'px' // 设置左侧区域的宽度
            left[i].style.width = moveLen + 19 + 'px'
          }
        }
        var endBox = function() {
          isPress = false
        }
        resize[i].addEventListener('touchstart', startBox)
        resize[i].addEventListener('touchmove', moveBox)
        resize[i].addEventListener('touchend', endBox)
      }
    },

    show(item) {
      const file = {
        name: 'index_wyc.png',
        resource_id: 'efac851f-4cd6-46d5-8a16-e585caa25191',
        resource_id2: 'efac851f-4cd6-46d5-8a16-e585caa25191',
        task_id: null,
        upload_progress: 1,
        process_progress: 0,
        query_interval: null,
        processed_url: null,
        processed_url2: item.imgUrl,
        key: 'tasks/input/watermark/9e25d507-f6bb-4c0c-a5b4-106a703d942a.png',
        status: 'uploaded',
        url: item.imgUrl,
        type: null,
        width: item.width,
        height: item.height,
        afterWidth: null,
        afterHeight: null,
        historyArray: [],
        hStep: -1,
        brushPath: [],
        points: [],
        eraserPath: [],
        rectangles: [],
        touched: true,
        image_thumb_url: null
      }
      if (file) {
        this.isShow = true
        this.$nextTick(() => {
          this.selectFile(file)
        })
      }
    },

    onConfirm: async function() {
      const resource = this.selectedFile
      this.currentDisplayProcessFile = JSON.parse(JSON.stringify(resource))

      var ratio
      if (resource.width < resource.afterWidth) {
        ratio = 1
      } else {
        ratio = resource.afterWidth / resource.width
      }

      const canvasCopy = document.createElement('canvas')
      const context = canvasCopy.getContext('2d')
      canvasCopy.width = resource.width
      canvasCopy.height = resource.height
      context.fillStyle = 'black'
      context.fillRect(0, 0, resource.width, resource.height)
      // 将 套索 加入画布
      var points = resource.points
      if (points.length > 0) {
        context.save()
        context.beginPath()
        for (var i = 0; i < points.length; ++i) {
          var path = points[i]
          if (path.length > 2) {
            context.moveTo(path[0].x / ratio, path[0].y / ratio)
            for (var j = 1; j < path.length; ++j) { context.lineTo(path[j].x / ratio, path[j].y / ratio) }
          }
        }
        context.closePath()
        context.clip()
        context.fillStyle = 'white'
        context.fillRect(0, 0, resource.width, resource.height)
        context.restore()
      }
      // 将 画笔 加入画布
      var brushPath = resource.brushPath
      for (let i = 0; i < brushPath.length; ++i) {
        const path = brushPath[i]
        context.beginPath()
        if (path.length === 1) {
          context.lineWidth = 1
          context.strokeStyle = 'white'
          context.arc(
            path[0].x / ratio,
            path[0].y / ratio,
            path[0].size / ratio / 2,
            0,
            2 * Math.PI
          )
          context.stroke()
          context.fillStyle = 'white'
          context.fill()
        } else {
          context.lineWidth = path[0].size / ratio
          context.lineCap = 'round'
          context.lineJoin = 'round'
          context.strokeStyle = 'white'
          context.moveTo(path[0].x / ratio, path[0].y / ratio)
          for (let j = 1; j < path.length; ++j) { context.lineTo(path[j].x / ratio, path[j].y / ratio) }

          context.stroke()
        }
      }
      // 将 橡皮擦 加入画布
      var eraserPath = resource.eraserPath
      for (let i = 0; i < eraserPath.length; ++i) {
        const path = eraserPath[i]
        for (let j = 0; j < path.length; ++j) {
          context.save()
          context.beginPath()
          context.arc(path[j].x, path[j].y, path[j].size / 2, 0, Math.PI * 2)
          context.clip()
          context.clearRect(
            path[j].x - path[j].size / 2,
            path[j].y - path[j].size / 2,
            path[j].size,
            path[j].size
          )
          context.restore()
        }
      }
      // 将 矩形 加入画布
      context.fillStyle = 'white'
      var rectangles = resource.rectangles.filter(function(ele) {
        return !ele.isHidden
      })
      for (let i = 0; i < rectangles.length; i++) {
        context.fillRect(
          Math.floor(rectangles[i].x / ratio),
          Math.floor(rectangles[i].y / ratio),
          Math.floor(rectangles[i].width / ratio),
          Math.floor(rectangles[i].height / ratio)
        )
      }

      // 将画布内容导出
      const mask_base64 = canvasCopy.toDataURL('image/png')

      const data = {
        maskBase64: mask_base64
      }
      this.isShow = false
      this.$emit('maskResult', data)
      // mask_base64 = mask_base64.substring(mask_base64.indexOf(",") + 1);
      // console.log("mask_base64", mask_base64)
    }
  }
}
</script>

<style scoped>
</style>
